# if condition:
# statement
# ---optional!---
# elif condition:
# statement
# elif condition:
# statement
# else:
# statement
exam1=90; exam2=85
if(exam1>=90) and (exam2>=90):
print('Excellent!')3 Control Flows
3.0.0.1 - Control statements in Python
- Conditional Constructs : if
- Loops : for, while
3.1 Statements & Comments
3.2 if Conditionals
if(exam1>=90) | (exam2>=90):
print('Good')Good
a=10
if a>10:
print("a>10")
else:
print("a=10")a=10
# Exercise 1
a=[1,2,3,4,6,7,9]
b=a.copy()
b.sort()
if a==b:
print("a is sorted")
else:
print("a is not sorted")a is sorted
# Exercise2
x=[1,2,3,4,5,6,7,8]
x_sort=x.copy()
x.sort()
len_x=len(x_sort)
mid_even=(x_sort[int(len(x_sort)/2-1)]+x_sort[int(len(x_sort)/2)])/2
mid_odd=x_sort[int(len(x_sort)//2)]
if len(x_sort)%2==0:
print("n={}이고, 중간값은 {}입니다.".format(len_x,mid_even))
elif len(x_sort)%2==1:
print("n={}이고, 중간값은 {}입니다.".format(len_x,mid_odd))
else :
print("중간값을 산출할 수 없습니다.")n=8이고, 중간값은 4.5입니다.
3.3 Loops - for loop
# for interating_var in iterable:
# statements# exercise 3
a=input("When you enter...")
a_int=int(a)
print("Input a number: "+a,
"The output will be...",
sep="\n")
for i in range(1,10):
print(a+" x "+str(i)+" = "+str(a_int*i))Input a number: 99
The output will be...
99 x 1 = 99
99 x 2 = 198
99 x 3 = 297
99 x 4 = 396
99 x 5 = 495
99 x 6 = 594
99 x 7 = 693
99 x 8 = 792
99 x 9 = 891
# exercise 4
sum_even=0
sum_odd=0
for i in range(10001):
if i%2==0:
sum_even+=i
else:sum_odd+=i
print(sum_even,
sum_odd,
sum_even+sum_odd,
sep='\n')25005000
25000000
50005000
# exercise 5
fibonacci=[1,1]
for i in range(10):
fibonacci.append(fibonacci[i]+fibonacci[i+1])
print(
fibonacci,
sum(fibonacci),
sep='\n'
)[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
376
# exercise 6
a=input("When you enter alpha-num string...")
letter_index=list()
digits_index=list()
non_index=list()
print(
"Sample Data : "+a,
"The output will be...",
sep='\n'
)
for i in range(0,len(a)):
if a[i].isalpha():
letter_index.append(i)
elif a[i].isnumeric():
digits_index.append(i)
else: non_index.append(i)
print(
"Letters {} at {}".format(len(letter_index),letter_index),
"Digits {} at {}".format(len(digits_index),digits_index),
"And there are {} at {} which are NOT alphanumeric".format(len(non_index),non_index),
sep='\n'
)Sample Data : sample asdfl11231,2,1,3.2 21
The output will be...
Letters 11 at [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11]
Digits 11 at [12, 13, 14, 15, 16, 18, 20, 22, 24, 27, 28]
And there are 7 at [6, 17, 19, 21, 23, 25, 26] which are NOT alphanumeric